package ReentrantLock_3;
import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
            Thread.sleep(20); // 模拟资源访问时间
            System.out.println(Thread.currentThread().getName() + " 增加计数: " + count);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
}

public class 基本ReentrantLock使用_计数器 {
    public static void main(String[] args) {
        final Counter counter = new Counter();
        // 创建50个增加计数的线程
        for (int i = 0; i < 50; i++) {
            new Thread(new Runnable() {
                public void run() {
                    counter.increment();
                }
            }, "计数线程-" + i).start();
        }
    }
}
